package cn.cqvie.service.impl;

import cn.cqvie.common.BaseContext;
import cn.cqvie.dao.EmployeeDao;
import cn.cqvie.pojo.Employee;
import cn.cqvie.pojo.Role;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsPasswordService;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.List;

@Component
public class EmployeeDetailService implements UserDetailsService, UserDetailsPasswordService {
    @Autowired
    private EmployeeDao employeeDao;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername,username);
        Employee employee = employeeDao.selectOne(queryWrapper);
        if(ObjectUtils.isEmpty(employee)){
            throw new UsernameNotFoundException("用户名不存在");
        }
        List<Role> role = employeeDao.findRole(employee.getId());
        employee.setRoles(role);
        return employee;
    }

    @Override
    public UserDetails updatePassword(UserDetails user, String newPassword) {
        Integer integer = employeeDao.updateUserPassword(user.getUsername(), newPassword);
        if (integer==1){
            ((Employee)user).setPassword(newPassword);
        }
        return user;
    }
}
